package com.yuesystem.config;


import com.yuesystem.common.JacksonObjectMapper;
import com.yuesystem.interceptor.PermisssionInterceptor;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;



/**
 * Web配置类.
 */
@Configuration
@Slf4j
public class WebMvcConfig extends WebMvcConfigurationSupport {
  
  @Autowired
  private PermisssionInterceptor permisssionInterceptor;
  
  // 这个方法是用来配置静态资源的，比如html，js，css，等等
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
  }
  
  /**
   * 配置拦截哪些页面.
   *
   * @param registry 注册
   */
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(permisssionInterceptor)
        .addPathPatterns("/**")    // 拦截哪些页面
        .excludePathPatterns(
            "/users/login",
            "/users/register",
            "/users/logout",
            "/users/send",
            "/users/forget",
            "/items/**",
            "/academies/**",
            "/blogs/list",
            "/blogs/commentFirst/**",
            "/blogs/commentTwo/**",
            "/blogs/blogOneList/{blogId}",
            "/blogs/comment/{blogId}",
            "/visual/**",
            "/offices/**",
            "/items2/**",
            "/visual2/**",
            "/question/**",
            "/notices/**",
            "/feedback/**",
            "/collects/**"
        );   // 放行哪些页面
  }
  
  /**
   * 扩展MVC框架的消息转换器.
   *
   * @param converters 变换器
   */
  @Override
  protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    log.info("扩展我们自己的消息转换器...");
    
    // 创建消息转换器对象
    MappingJackson2HttpMessageConverter messageConverter =
        new MappingJackson2HttpMessageConverter();
    
    // 设置对象转换器，底层使用JacksonObjectMapper将Java对象转为Json
    messageConverter.setObjectMapper(new JacksonObjectMapper());
    
    // 将上面的消息转换器对象追加到MVC集合中
    converters.add(0, messageConverter); //增加索引，把我们的转换器放到最前面，用的时候就可以用我们的了
  }
  
  /**
   * 跨域配置.
   *
   * @param registry 注册
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    // 设置允许跨域的路径
    registry.addMapping("/**")
        // 设置允许跨域请求的域名
        .allowedOriginPatterns("*")
        // 是否允许证书
        .allowCredentials(true)
        // 设置允许的方法
        .allowedMethods("*")
        // 设置允许的header属性
        .allowedHeaders("*")
        // 允许跨域时间
        .maxAge(3600);
  }
  
}
